import * as userService from '../../services/user';
import * as groupService from '../../services/group';

export default {

  namespace: 'user',

  state: {
    userList: [],
    // groupList: [],
    name: [],
    gid: [],
  },

  effects: {

    *queryList({ payload = [] }, { call, put }) {
      console.log("queryList payload");
      const {gid = [], name = []} = payload;

      const rsp1 = yield call(groupService.queryList);
      console.log('queryGroupList');
      console.log(rsp1.data);
      yield sessionStorage.setItem('groupList', JSON.stringify(rsp1.data));

      const rsp = yield call(userService.queryList, name, gid);
      console.log('queryList');
      console.log(rsp.data);

      yield put({ type: 'saveList', payload: { userList: rsp.data, name: name, gid: gid }});
    },
    *deleteOne({ payload }, { select, call, put }) {
      console.log('delete one payload' + payload);
      yield call(userService.deleteOne, payload);
      const user = yield select(state => state.user);
      yield put({ type: 'queryList', payload: { ...user } });
    },
    *addOne({ payload }, { select, call, put }) {
      const rsp = yield call(userService.addOne, payload);
      const user = yield select(state => state.user);
      console.log(user);
      yield put({ type: 'queryList', payload: { ...user } });
      return rsp;
    },
    *updateOne({ payload }, { select, call, put }) {
      console.log(`update`);
      console.log(payload)
      const rsp = yield call(userService.updateOne, payload);

      const user = yield select(state => state.user);
      console.log(user);
      yield put({ type: 'queryList', payload: { ...user } });
      return rsp;
    }
  },

  reducers: {
    saveList(state, { payload: { userList, name, gid } }) {
      return {
        ...state,
        userList,
        name,
        gid,
      }
    }
  },
  subscriptions: {
    setup({ dispatch }){
      dispatch({
        type: 'queryList',
      });
    }
  },
};
